package eco.footprint;

import java.text.MessageFormat;
import java.util.Arrays;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.XmlResourceParser;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class FootprintTestActivity extends Activity {
	boolean mFullTest = false;
	int[] questionsBasicArray = new int[] { 0, 4, 9, 18, 19, 20, 21, 22, 23,
			24, 25, 32, 33, 34, 35, 36, 37, 38, 41 };
	int[] questionsFullArray = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
			11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
			28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41 };
	int[] mCurrentSet = new int[] {};
	FootprintUtil util = new FootprintUtil();

	Question[] mQuestions = null;

	int mCurrentSetQuestionNum = -1;
	int mCurrentQuestion = -1;

	int[] answers = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.test);
		Intent i = getIntent();

		mFullTest = i.getBooleanExtra("full_test", false);
		if (mFullTest)
			mCurrentSet = questionsFullArray;
		else {
			mCurrentSet = questionsBasicArray;
		}
		Button btnBack = (Button) findViewById(R.id.btnBack);
		btnBack.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				if (mCurrentSetQuestionNum > 0) {
					mCurrentSetQuestionNum--;
					mCurrentQuestion = mCurrentSet[mCurrentSetQuestionNum];
					nextQuestion();
				} else {
					setResult(RESULT_CANCELED);
					finish();
				}

			}
		});

		Button btnNext = (Button) findViewById(R.id.btnNext);
		btnNext.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				FootprintResult r = util.calculateFootprintFromAnswers(answers);
				if (mCurrentSetQuestionNum < mCurrentSet.length - 1) {
					generateIndicator(r);
					mCurrentSetQuestionNum++;
					mCurrentQuestion = mCurrentSet[mCurrentSetQuestionNum];
					nextQuestion();
				} else {
					Intent i = new Intent(FootprintTestActivity.this,
							FootprintSummaryActivity.class);
					i.putExtra("result", r);

					int[] questions = util.sortQuestionsByInfluence(answers);

					XmlResourceParser xrp = getResources().getXml(R.xml.tips);
					util.initTips(xrp);

					String[] tips = util.getTipsByQuestions(questions);
					i.putExtra("tips", tips);

					startActivityForResult(i, 0);

				}
			}
		});

		SharedPreferences preferences = PreferenceManager
				.getDefaultSharedPreferences(this);

		int units = Integer.valueOf(preferences.getString("unitSystem", "1"));
		int questionResId = (units == 1) ? R.xml.questions
				: R.xml.questions_ems;

		XmlResourceParser xrp = getResources().getXml(questionResId);

		util.initQuestions(xrp);
		xrp = getResources().getXml(R.xml.clum_data);
		util.initCategories(xrp);
		mQuestions = util.mQuestions;
		answers = new int[mQuestions.length];
		Arrays.fill(answers, -1);
		mCurrentSetQuestionNum++;
		mCurrentQuestion = mCurrentSet[mCurrentSetQuestionNum];
		nextQuestion();
	}

	private void nextQuestion() {
		final Question q = mQuestions[mCurrentQuestion];

		TextView txtNumber = (TextView) findViewById(R.id.txtNumber);
		txtNumber.setText(MessageFormat.format("{0}/{1}",
				mCurrentSetQuestionNum + 1, mCurrentSet.length));

		TextView txtQuestion = (TextView) findViewById(R.id.txtQuestion);
		txtQuestion.setText(q.mQuestion);

		ScrollView viewRGQuestion = (ScrollView) findViewById(R.id.viewRGQuestion);
		ScrollView viewSLQuestion = (ScrollView) findViewById(R.id.viewSLQuestion);

		final TextView txtAnswer = (TextView) findViewById(R.id.txtAnswer);
		if (q.mType == Question.TYPE_RADIOBUTTON) {
			viewRGQuestion.setVisibility(View.VISIBLE);
			viewSLQuestion.setVisibility(View.GONE);
			withRadioButtons(q, txtAnswer);
		} else {
			viewSLQuestion.setVisibility(View.VISIBLE);
			viewRGQuestion.setVisibility(View.GONE);
			withSeekBar(q, txtAnswer);
		}
	}

	private void withRadioButtons(final Question q, final TextView txtAnswer) {

		RadioGroup rgAnswer = (RadioGroup) findViewById(R.id.rdgAnswer);
		rgAnswer.removeAllViews();
		makeRadioButtons(rgAnswer, q.mAnswers, answers[mCurrentQuestion]);
		rgAnswer.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(RadioGroup rg, int index) {
				answers[mCurrentQuestion] = index;
			}
		});
	}

	private void withSeekBar(final Question q, final TextView txtAnswer) {
		final SeekBar sbAnswer = (SeekBar) findViewById(R.id.sbAnswer);
		Button txtLeft = (Button) findViewById(R.id.btnLeft);
		txtLeft.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				int p = sbAnswer.getProgress();
				if (p > 0)
					p--;
				sbAnswer.setProgress(p);
			}
		});

		Button txtRight = (Button) findViewById(R.id.btnRight);
		txtRight.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				int p = sbAnswer.getProgress();
				if (p < sbAnswer.getMax())
					p++;
				sbAnswer.setProgress(p);
			}
		});

		txtLeft.setText(q.mMinText);
		txtRight.setText(q.mMaxText);
		int max = q.mAnswers.length - 1;
		sbAnswer.setMax(max);
		int pos = answers[mCurrentQuestion] == -1 ? (max / 2)
				: answers[mCurrentQuestion];
		answers[mCurrentQuestion] = pos;
		sbAnswer.setProgress(pos);
		txtAnswer.setText(q.mAnswers[sbAnswer.getProgress()].mAnswer);
		sbAnswer.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			public void onProgressChanged(SeekBar sb, int p, boolean touch) {
				Question currentQuestion = mQuestions[mCurrentQuestion];
				Answer newAnswer = currentQuestion.mAnswers[p];
				txtAnswer.setText(newAnswer.mAnswer);
				answers[mCurrentQuestion] = p;
			}

			public void onStartTrackingTouch(SeekBar seekBar) {
			}

			public void onStopTrackingTouch(SeekBar seekBar) {
			}
		});
	}

	public void makeRadioButtons(RadioGroup radioGroup, Answer[] answers,
			int answer) {
		LayoutInflater inflater = LayoutInflater.from(this);
		for (int i = 0; i < answers.length; i++) {
			{

				RadioButton rb = (RadioButton) inflater.inflate(
						R.layout.radiobutton, null);
				rb.setId(i);
				rb.setSaveEnabled(false);
				rb.setChecked(answer != -1 && answer == i);
				rb.setText(answers[i].mAnswer);
				rb.setTextSize(TypedValue.COMPLEX_UNIT_PT, 8);
				radioGroup.addView(rb);
			}
		}
		radioGroup.clearCheck();
	}

	// Listen for results.
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		setResult(resultCode);
		finish();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("mCurrentQuestion", mCurrentQuestion);
		outState.putIntArray("answers", answers);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mCurrentQuestion = savedInstanceState.getInt("mCurrentQuestion");
		mCurrentSetQuestionNum = Arrays.binarySearch(mCurrentSet,
				mCurrentQuestion);
		answers = savedInstanceState.getIntArray("answers");
		generateIndicator(util.calculateFootprintFromAnswers(answers));
		nextQuestion();
	}

	private void generateIndicator(FootprintResult r) {
		int ceil = (int) Math.ceil(r.numberOfEarths);
		Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
				R.drawable.earth);
		int dw = bitmap.getWidth();
		int h = bitmap.getHeight();
		int w = (int) Math.ceil(dw * r.numberOfEarths);
		Bitmap result = Bitmap.createBitmap(w, h, Config.RGB_565);
		Canvas canvas = new Canvas(result);
		canvas.drawColor(getResources().getColor(R.color.bg2Color));
		int x = 0;
		Paint p = new Paint();
		for (int i = 0; i < ceil; i++) {
			canvas.drawBitmap(bitmap, x, 0, p);
			x += dw;
		}
		ImageView imgEarth = (ImageView) findViewById(R.id.imgEarth);
		imgEarth.setImageBitmap(result);
		TextView txtResult = (TextView) findViewById(R.id.txtResult);
		txtResult.setText(MessageFormat.format("{0} {1, number, #.##}",
				getResources().getString(R.string.lbEarths), r.numberOfEarths));
	}

}